package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @version 1.8
 * @Author Djx_hmbb
 * @Date 2023/10/10 8:20
 * @注释:Tcp回显客户端
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String server,int port) throws IOException {
        //Socket 构造方法，能识别点分十进制的IP地址，比DatagramSocket 方便
        //new 对象的同时，就会进行Tcp连接操作
        socket = new Socket(server, port);
    }
    public void start(){
        System.out.println("客户端启动!");
        Scanner s = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()){
            while (true){
                //1.先从键盘上读取用户输入的内容
                System.out.print(">");
                String request = s.next();
                if(request.equals("exit")){
                    System.out.println("退出客户端!");
                    break;
                }
                //2.把读到的内容构造成请求，发送给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //刷新一下,确保消息发出去了
                printWriter.flush();
                //3.读取服务器的响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();
                //4.把响应内容显示到界面上
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
